package com.wondersgroup.fjzlpt.plat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.wondersgroup.fjzlpt.plat.dao.inter.AuthUserDAO;
import com.wondersgroup.fjzlpt.plat.service.inter.PwdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by lion on 2017/8/25.
 */
@Service
public class PwdServiceImpl implements PwdService {

    @Autowired
    AuthUserDAO authUserDAO;

    @Override
    public JSONObject updatePwd(Map map) {
        ResultObject ro = new ResultObject();
        String USERID = (String)map.get("USERID");
        String hexOldPwd = (String)map.get("hexOldPwd");
        try{
            if(isRightPwd(USERID, hexOldPwd)){
                String hexNewPwd = (String)map.get("hexNewPwd");
                this.authUserDAO.updateUserPwd(USERID, hexNewPwd);
            }else{
                ro.changeFaultState("原始密码不正确，请重新输入");
            }
        }catch (BadPwdException e){
            ro.changeFaultState(e.getMessage());
        }
        catch (Exception e){
            ro.changeFaultState("修改密码失败");
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    /**
     * 原始密码是否正确
     * @param userId
     * @param hexOldPwd
     * @return
     */
    private boolean isRightPwd(String userId, String hexOldPwd){
        try{
            String oldPassword = this.authUserDAO.queryUserPwd(userId);
            return oldPassword.equals(hexOldPwd);
        }catch (Exception e){
            throw new BadPwdException("查询用户原始密码失败", e);
        }
    }

    class BadPwdException extends RuntimeException{
        public BadPwdException(String msg, Exception e){
            super(msg, e);
        }
    }
}
